import axios from 'axios'
import { getToken } from '@/utils/auth'
import { ElMessageBox, ElMessage } from 'element-plus'
// import { useRouter } from 'vue-router'
import router from '@/router'
import store from '@/store/index'
// 提示名单
import toastList from './whiteList'
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL,
  timeout: 50000,
})

console.log('process.env = ' + JSON.stringify(process.env))
service.interceptors.request.use(
  (config) => {
    config.headers['auth'] = getToken()
    config.headers['Access-Control-Allow-Origin'] = '*'
    return config
  },
  (error) => {
    console.log(error)
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response) => {
    const res = response.data
    if (res.code !== '0000') {
      const warningCodes = ['2001', '2006']
      const errorCodes = ['2006', '2007']
      if (warningCodes.includes(res.code)) {
        ElMessageBox.confirm(res.message, '提示', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            // location.reload()
            router.push({ path: '/login' })
          })
        })
        return Promise.reject(new Error(res.message || 'Error'))
      } else if (errorCodes.includes(res.code)) {
        router.push({ path: '/OtherError', query: { code: res.code } })
        return Promise.reject(new Error(res.message || 'Error'))
      } else {
        ElMessage.error(res.message)
        return Promise.reject(new Error(res.message || 'Error'))
      }
    } else {
      // TODO 注册一个提交给提示的白名单
      // ElMessage.success({ message: '调用成功', type: 'success' })
      if (toastList && toastList[response.config.url]) {
        ElMessage.success({
          message: toastList[response.config.url],
          type: 'success',
        })
      }
      console.log('toastList =' + JSON.stringify(toastList))
      return res
    }
  },
  (error) => {
    // TODO 短时间内只有一次报错
    if (error.message === 'Network Error') {
      ElMessage.error('网络差，操作失败，请稍后再试')
    }
    return Promise.reject(error)
  }
)

export default service
